package cn.com.jenson.service.auth.service.impl;

import cn.com.jenson.dao.login.bo.LoginBo;
import cn.com.jenson.dao.login.vo.LoginVo;
import cn.com.jenson.dao.user.vo.UserVo;
import cn.com.jenson.entity.user.User;
import cn.com.jenson.exception.BusinessException;
import cn.com.jenson.service.auth.service.LoginService;
import cn.com.jenson.service.user.repository.UserRepository;
import cn.com.jenson.service.user.service.UserService;
import cn.com.jenson.util.JWTUtil;
import cn.com.jenson.util.MD5Util;
import cn.com.jenson.util.StringUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserService userService;

    @Override
    public LoginVo webLogin(LoginBo loginBo) throws InstantiationException, IllegalAccessException {
        User user = userRepository.findByAccountAndDeleted(loginBo.getAccount(), false);
        if (Objects.isNull(user))
            throw new BusinessException("账户或密码错误");
        String password = MD5Util.cryptographicString(loginBo.getPassword(), user.getEncipher());
        if (!user.getPassword().equals(password))
            throw new BusinessException("账户或密码错误!");
        UserVo userVo = new UserVo().fromEntity(user, UserVo.class);
        userService.supplement(userVo);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(JWTUtil.getToken(userVo));
        loginVo.setUserVo(userVo);
        return loginVo;
    }
}
